//
// Created by ziya on 2025/5/21.
//

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "buffer.h"

#define INITIAL_CAPACITY 16

void buffer_init(buffer *buf) {
    buf->capacity = INITIAL_CAPACITY;
    buf->length = 0;
    buf->data = (char *)malloc(buf->capacity);
    buf->data[0] = '\0';
}

void buffer_append(buffer *buf, char c) {
    if (buf->length + 1 >= buf->capacity) {
        buf->capacity *= 2;
        buf->data = (char *)realloc(buf->data, buf->capacity);
    }

    buf->data[buf->length++] = c;
    buf->data[buf->length] = '\0';
}

const char* buffer_cstr(buffer *buf) {
    return buf->data;
}

void buffer_free(buffer *buf) {
    free(buf->data);
    buf->data = NULL;
    buf->length = buf->capacity = 0;
}

